<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1200" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #questions>
        <Question
          v-for="(question, index) in questions"
          :key="index"
          :question="question"
        />
        <draggable v-model="questionBank">
          <template #item=" element ">
          <component
            v-for="(item, index) in questionBank"
            :key="index"
            :is="item.type"
            :question="item"
          />
          </template>
        </draggable>
      </template>

    </BasicForm>
  </BasicModal>
</template>

<script lang="ts">
import { ref, computed, unref, defineComponent,defineEmits } from "vue";
import draggable from 'vuedraggable';
import {BasicModal, useModalInner} from '/@/components/Modal';
import {BasicForm, useForm} from '/@/components/Form/index';
import {formSchema} from '../ExamTestQuestions.data';
import {saveOrUpdate} from '../ExamTestQuestions.api';
import { loadTreeData } from "/@/views/exam/category/category.api";
import Question from './Question.vue';
import SingleChoiceQuestion from './SingleChoiceQuestion.vue';
import MultipleChoiceQuestion from './MultipleChoiceQuestion.vue';
import FillInTheBlanksQuestion from './FillInTheBlanksQuestion.vue';
import TrueOrFalseQuestion from './TrueOrFalseQuestion.vue';
import EssayQuestion from './EssayQuestion.vue';
import { propTypes } from "/@/utils/propTypes";
export default defineComponent({
  name: "ExamTestQuestionsForm",
  components:{
    BasicModal,
    BasicForm,
    draggable,
    Question,
    SingleChoiceQuestion,
    MultipleChoiceQuestion,
    FillInTheBlanksQuestion,
    TrueOrFalseQuestion,
    EssayQuestion
  },
  props:{
    formData: propTypes.object.def({}),
    questionnaireName: {
      type: String,
      required: true
    },
    questionnaireCategory: {
      type: String,
      required: true
    },
    questions: {
      type: Array,
      required: true
    },
    disabled:{

    }
  },
  setup(props){
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const treeData = ref([]);
    const expandedRowKeys = ref([]);
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate,updateSchema}] = useForm({
      //labelWidth: 150,
      schemas: formSchema,
      showActionButtonGroup: false,
      baseColProps: {span: 24}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
      //重置表单
      await resetFields();
      setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
      isUpdate.value = !!data?.isUpdate;
      expandedRowKeys.value = [];
      if (unref(isUpdate)) {
        //表单赋值
        await setFieldsValue({
          ...data.record,
        });
      }
      // 隐藏底部时禁用整个表单
      setProps({ disabled: !data?.showFooter })
      //父级节点树信息
      treeData.value = await loadTreeData({ async: false, pid: '' });
      await updateSchema({
        field: 'categoryId',
        componentProps: { treeData },
      });
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
    //表单提交事件
    async function handleSubmit(v) {
      try {
        let values = await validate();
        setModalProps({confirmLoading: true});
        //提交表单
        await saveOrUpdate(values, isUpdate.value);
        //关闭弹窗
        closeModal();
        //刷新列表
        emit('success', { isUpdate: unref(isUpdate), values: { ...values }, expandedArr: unref(expandedRowKeys).reverse() });
      } finally {
        setModalProps({confirmLoading: false});
      }
    }
    /**
     * 根据pid获取展开的节点
     * @param pid
     * @param arr
     */
    function getExpandKeysByPid(pid, arr) {
      if (pid && arr && arr.length > 0) {
        debugger
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].key == pid && unref(expandedRowKeys).indexOf(pid) < 0) {
            expandedRowKeys.value.push(arr[i].key);
            getExpandKeysByPid(arr[i]['parentId'], unref(treeData));
          } else {
            getExpandKeysByPid(pid, arr[i].children);
          }
        }
      }
    }
    return {
      registerForm,
      isUpdate,
      title,
      treeData,
      expandedRowKeys,
      registerModal,
      handleSubmit,
      SingleChoiceQuestion,
      MultipleChoiceQuestion,
      FillInTheBlanksQuestion,
      TrueOrFalseQuestion,
      EssayQuestion,
      BasicForm,
      questions: [],
      questionBank: [
        { type: 'SingleChoiceQuestion', title: '单选题 1', options: ['A', 'B', 'C'] },
        { type: 'MultipleChoiceQuestion', title: '多选题 1', options: ['A', 'B', 'C', 'D'] },
        { type: 'FillInTheBlanksQuestion', title: '填空题 1', blanks: 2 },
        { type: 'TrueOrFalseQuestion', title: '判断题 1' },
        { type: 'EssayQuestion', title: '解答题 1' },
      ],
    }
  }
});
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number){
  width: 100%
}

:deep(.ant-calendar-picker){
  width: 100%
}
</style>
